package com.py.credit.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.constant.ResourcePath;
import com.py.credit.entity.SysUser;
import com.py.credit.service.ModelBaseService;
import com.py.credit.service.ModelTestService;
import com.py.credit.service.XypjRemoteBaseService;
import com.py.credit.service.ReportContentService;
import com.py.credit.service.ScoreRunningService;
import com.py.credit.utils.HtmlToPdfUtils;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

@RestController
@RequestMapping(value = "/reportContent")
public class ReportContentController {

	private static final int ZERO = 0;

	private static final String ZERO_STR = "0";

	private final static String FRONT_TABLE_ID = "reportContent";

	@Value("${absolutepath}")
	private String absolutepath;

	@Value("${pdfJsPath}")
	private String pdfJsPath;

	@Value("${googlePath}")
	private String googlePath;

	@Value("${pdfPagePath}")

	private String pdfPagePath;

	@Value("${pdfForXypjPagePath}")

	private String pdfForXypjPagePath;

	@Autowired
	private ReportContentService reportContentService;

	@Autowired
	private XypjRemoteBaseService xypjRemoteBaseService;

	@Autowired
	private ScoreRunningService scoreRunningService;

	@Autowired
	private ModelTestService modelTestService;

	@Autowired
	private ModelBaseService modelBaseService;

	@RequestMapping(value = "/searchFinance.json")
	public RestServiceResult<List<Map>> searchFinance(String userId, String bgbh, HttpServletResponse response,
			HttpServletRequest request) {
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			List<Map> list = reportContentService.searchFinance(userId);
			result.setData(list);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("更新模型指标值异常，请稍后再试！");
			ExceptionLogger.error("更新模型指标值异常！", e.getMessage(), e);
			return result;
		}
	}

	@RequestMapping(value = "/searchprofits.json")
	public RestServiceResult<List<Map>> searchprofits(String userId, String bgbh, HttpServletResponse response,
			HttpServletRequest request) {
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			List<Map> list = reportContentService.searchprofits(userId);
			result.setData(list);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("更新模型指标值异常，请稍后再试！");
			ExceptionLogger.error("更新模型指标值异常！", e.getMessage(), e);
			return result;
		}
	}

	@RequestMapping(value = "/searchCashflow.json")
	public RestServiceResult<List<Map>> searchCashflow(String userId, String bgbh, HttpServletResponse response,
			HttpServletRequest request) {
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			List<Map> list = reportContentService.searchCashflow(userId);
			result.setData(list);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("更新模型指标值异常，请稍后再试！");
			ExceptionLogger.error("更新模型指标值异常！", e.getMessage(), e);
			return result;
		}
	}

	@RequestMapping(value = "/searchAssets.json")
	public RestServiceResult<List<Map>> searchAssets(String userId, String bgbh, HttpServletResponse response,
			HttpServletRequest request) {
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			List<Map> list = reportContentService.searchAssets(userId);
			result.setData(list);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("更新模型指标值异常，请稍后再试！");
			ExceptionLogger.error("更新模型指标值异常！", e.getMessage(), e);
			return result;
		}
	}

	@RequestMapping(value = "/searchcurrentliabilities.json")
	public RestServiceResult<List<Map>> searchcurrentliabilities(String userId, String bgbh,
			HttpServletResponse response, HttpServletRequest request) {
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			List<Map> list = reportContentService.searchcurrentliabilities(userId);
			result.setData(list);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("更新模型指标值异常，请稍后再试！");
			ExceptionLogger.error("更新模型指标值异常！", e.getMessage(), e);
			return result;
		}
	}

	@RequestMapping(value = "/getReport.json")
	public Map getReport(String bgbh, HttpServletResponse response, HttpServletRequest request) {
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();
		try {
			// List<Map>
			// list=reportContentService.searchcurrentliabilities(userId);

			Map<String, String> evalInfo = reportContentService.getEvalInfo(bgbh);
			List<Map> listModelRanks = modelBaseService.getRankList(evalInfo.get("model_id"));
			String sqr = String.valueOf(evalInfo.get("sqr"));
			String tybm = reportContentService.getTybm(sqr);
			List<Map> financeList = reportContentService.searchFinance(sqr);
			List<Map> profitList = reportContentService.searchprofits(sqr);
			List<Map> assetList = reportContentService.searchAssets(sqr);
			List<Map> liabilitiesList = reportContentService.searchcurrentliabilities(sqr);
			List<Map> cashflowList = reportContentService.searchCashflow(sqr);
			List<Map> qyxx = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_1000000010014_lfsxnk85kf", tybm);
			List<Map> holderList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_1000000010013_8hPE5lWX7N", tybm);
			List<Map> branchList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_1000000010010_aiPIZu8BZF", tybm);
			List<Map> changeList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_1000000010009_L6GvGS42NY", tybm);
			List<Map> mainList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_1000000010012_7AnbGEhbmt", tybm);
			Map mapAll = new HashMap();
			mapAll.put("listModelRanks", listModelRanks);
			mapAll.put("financeList", financeList);
			mapAll.put("profitList", profitList);
			mapAll.put("assetList", assetList);
			mapAll.put("liabilitiesList", liabilitiesList);
			mapAll.put("cashflowList", cashflowList);
			mapAll.put("evalInfo", evalInfo);
			if (qyxx.size() > 0) {
				mapAll.put("qyxx", qyxx.get(0));
			}
			mapAll.put("holderList", holderList);
			mapAll.put("branchList", branchList);
			mapAll.put("changeList", changeList);
			mapAll.put("mainList", mainList);
			// result.setData(list);
			return mapAll;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("更新模型指标值异常，请稍后再试！");
			ExceptionLogger.error("更新模型指标值异常！", e.getMessage(), e);
			return null;
		}
	}

	@RequestMapping(value = "/getReportYz.json")
	public Map getReportYz(String tybm, String pcId, HttpServletResponse response, HttpServletRequest request) {
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();
		try {
			Map evalInfo = modelTestService.selectScoreInfoByTybmAndPcid(pcId, tybm);
			// 企业工商基础信息
			List<Map> qyxx = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_1000000010014_lfsxnk85kf", tybm);

			// 企业基本信息
			List<Map> jbxx = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020069_0QJsCT12ST", tybm);
			// 股东信息
			List<Map> holderList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_1000000010013_8hPE5lWX7N", tybm);
			// 分支机构
			List<Map> branchList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_1000000010010_aiPIZu8BZF", tybm);
			// 历史沿革
			List<Map> changeList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_1000000010009_L6GvGS42NY", tybm);
			// 董事会主要成员
			List<Map> mainList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_1000000010012_7AnbGEhbmt", tybm);
			// 企业对外投资
			List<Map> enterpriseForeignInvestmentList = xypjRemoteBaseService
					.getTableValuesByTybmAndTable("t_10000020035_31QqrjNQMI", tybm);
			// 法人对外投资
			List<Map> frForeignInvestmentList = xypjRemoteBaseService
					.getTableValuesByTybmAndTable("t_10000020038_CdPdYlgJIU", tybm);
			// 网站备案
			List<Map> webList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020067_zwmkA93VJk", tybm);
			// 执行公告
			List<Map> executiveAnnouncementList = xypjRemoteBaseService
					.getTableValuesByTybmAndTable("t_10000020055_ooWilKgE1a", tybm);
			// 法院公告
			List<Map> courtAnnouncementList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020056_FqHbBIP5wW",
					tybm);
			// 裁判文书
			List<Map> referBookList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020057_VqVvAlMpeL", tybm);
			// 开庭公告
			List<Map> announcementCourtSessionList = xypjRemoteBaseService
					.getTableValuesByTybmAndTable("t_10000020058_NdGY8UTaWV", tybm);
			// 欠税公告
			List<Map> taxArrearList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020068_omagh7XEue", tybm);
			// 行政处罚
			List<Map> adPenaltyList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020047_4z8Y6U03BN", tybm);
			// 失信被执行人
			List<Map> loseCreditList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020053_ixye65DjaA", tybm);
			// 商标注册
			List<Map> logoList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020064_q7zexUMvJF", tybm);
			// 知识产权
			List<Map> intellectualPropertyRightList = xypjRemoteBaseService
					.getTableValuesByTybmAndTable("t_10000020065_7ZTo0ASgjr", tybm);
			// 税务评级
			List<Map> taxRankList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020066_m4N6fK4BDU", tybm);
			Map mapAll = new HashMap();
			mapAll.put("evalInfo", evalInfo);
			if (qyxx.size() > 0) {
				mapAll.put("qyxx", qyxx.get(0));
			}
			/*
			 * if(jbxx.size()>0){ mapAll.put("jbxx", jbxx.get(0)); }
			 */
			mapAll.put("holderList", holderList);
			mapAll.put("branchList", branchList);
			mapAll.put("changeList", changeList);
			mapAll.put("mainList", mainList);
			mapAll.put("enterpriseForeignInvestmentList", enterpriseForeignInvestmentList);
			mapAll.put("frForeignInvestmentList", frForeignInvestmentList);
			mapAll.put("webList", webList);
			mapAll.put("executiveAnnouncementList", executiveAnnouncementList);
			mapAll.put("courtAnnouncementList", courtAnnouncementList);
			mapAll.put("referBookList", referBookList);
			mapAll.put("announcementCourtSessionList", announcementCourtSessionList);
			mapAll.put("taxArrearList", taxArrearList);
			mapAll.put("adPenaltyList", adPenaltyList);
			mapAll.put("loseCreditList", loseCreditList);
			mapAll.put("logoList", logoList);
			mapAll.put("intellectualPropertyRightList", intellectualPropertyRightList);
			mapAll.put("taxRankList", taxRankList);
			// result.setData(list);
			return mapAll;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("更新模型指标值异常，请稍后再试！");
			ExceptionLogger.error("更新模型指标值异常！", e.getMessage(), e);
			return null;
		}
	}

	@RequestMapping(value = "/reportExport.do")
	public RestServiceResult<List<Map<String, Object>>> reportExport(
			@RequestParam(value = "bgbh", required = true) String bgbh, String id, Page page,
			HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
		List<Map<String, Object>> rep = new ArrayList<>();
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				r.setCode(RestServiceResult.CODE_UNKNOW);
				r.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("ReportContentController#reportExport", "未获取到当前用户信息！");
				return r;
			}
		} else {
			r.setCode(user.getCode());
			r.setMsg(user.getMsg());
			return r;
		}
		try {
			Map m = reportContentService.getEvalInfo(bgbh);
			String ztmc = String.valueOf(m.get("ztmc"));
			String url = "http://10.10.136.57:8086/exportPdf/pdf.jsp?bgbh=" + bgbh;
			boolean googleConvent = HtmlToPdfUtils.googleConvent(pdfJsPath, url,
					absolutepath + ResourcePath.CREDIT_REPORT_DIR + bgbh, ztmc + ".pdf", null, false, googlePath);
			if (googleConvent) {
				r.setData(rep);
				return r;
			} else {
				r.setCode(RestServiceResult.CODE_UNKNOW);
				r.setMsg("生成报告失败");
				ExceptionLogger.error("ReportContentController#reportExport", "生成报告失败");
			}
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg(e.getMessage());
			ExceptionLogger.error("ReportContentController#reportExport", "前台报告历史查询失败");
		}
		r.setData(rep);
		return r;
	}

}
